<template>
  <div class="users-container">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>用户管理</span>
          <div class="search-box">
            <el-input
              v-model="searchKeyword"
              placeholder="搜索用户昵称/手机号/邮箱"
              prefix-icon="Search"
              clearable
              @clear="handleSearch"
              @keyup.enter="handleSearch"
            />
            <el-select
              v-model="statusFilter"
              placeholder="状态筛选"
              clearable
              @change="handleSearch"
            >
              <el-option
                v-for="item in statusOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
            <el-button type="primary" @click="handleSearch">搜索</el-button>
          </div>
        </div>
      </template>

      <!-- 用户列表 -->
      <el-table
        :data="userList"
        style="width: 100%"
        v-loading="loading"
        border
        :default-sort="{prop: 'id', order: 'ascending'}"
        class="compact-table"
        size="small"
        :cell-class-name="tableCellClassName"
        row-class-name="compact-row"
      >
        <!-- 序号 -->
        <el-table-column label="序号" width="60" align="center">
          <template #default="scope">
            {{ (currentPage - 1) * pageSize + scope.$index + 1 }}
          </template>
        </el-table-column>

        <!-- 头像 -->
        <el-table-column label="头像" width="70">
          <template #default="scope">
            <div class="image-cell">
              <el-avatar :size="30" :src="scope.row.avatar" class="table-image" />
            </div>
          </template>
        </el-table-column>

        <!-- 昵称 -->
        <el-table-column prop="nickname" label="昵称" min-width="100">
          <template #default="scope">
            <div class="title-cell">
              <span class="post-title-text">{{ scope.row.nickname || '-' }}</span>
            </div>
          </template>
        </el-table-column>

        <!-- 手机号 -->
        <el-table-column prop="phone" label="手机号" min-width="100" />

        <!-- 邮箱 -->
        <el-table-column prop="email" label="邮箱" min-width="150">
          <template #default="scope">
            <span>{{ scope.row.email || '-' }}</span>
          </template>
        </el-table-column>

        <!-- 签名 -->
        <el-table-column prop="signature" label="签名" min-width="150">
          <template #default="scope">
            <div class="post-content">
              <div class="post-text">
                <el-tooltip
                  v-if="scope.row.signature"
                  :content="scope.row.signature"
                  placement="top"
                >
                  <span>{{ truncateText(scope.row.signature, 30) }}</span>
                </el-tooltip>
                <span v-else>-</span>
              </div>
            </div>
          </template>
        </el-table-column>

        <!-- 注册时间 -->
        <el-table-column prop="register_time" label="注册时间" width="130">
          <template #default="scope">
            <div class="time-cell">
              <el-icon><Clock /></el-icon>
              <span>{{ formatDate(scope.row.register_time) }}</span>
            </div>
          </template>
        </el-table-column>

        <!-- 状态 -->
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <div class="status-container">
              <el-tag :type="getStatusType(scope.row.status)" class="status-tag" size="small">
                {{ getStatusText(scope.row.status) }}
              </el-tag>
              <div v-if="scope.row.remaining_ban_time" class="ban-time">
                剩余：{{ scope.row.remaining_ban_time }}
              </div>
            </div>
          </template>
        </el-table-column>

        <!-- 操作 -->
        <el-table-column label="操作" width="180">
          <template #default="scope">
            <div class="action-btn-group">
              <el-button 
                type="primary" 
                size="small" 
                @click="viewUserDetail(scope.row)"
                text
              >
                查看
              </el-button>
              <el-button 
                :type="getButtonType(scope.row.status)" 
                size="small" 
                @click="handleBanUser(scope.row)"
                :disabled="scope.row.status === -1 || scope.row.status === 2 || scope.row.status === 4"
                text
              >
                {{ getBanButtonText(scope.row.status) }}
              </el-button>
              <el-popconfirm
                title="确定要删除该用户吗？此操作不可恢复！"
                @confirm="handleDeleteUser(scope.row)"
                v-if="scope.row.status !== 2"
              >
                <template #reference>
                  <el-button type="danger" size="small" text>删除</el-button>
                </template>
              </el-popconfirm>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页器 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          background
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 用户详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="用户详情"
      width="80%"
    >
      <div v-if="currentUser.status !== 0" class="ban-info">
        <el-alert
          :type="getAlertType(currentUser.status)"
          :title="getStatusText(currentUser.status)"
          show-icon
        >
          <template #default>
            <p v-if="currentUser.remaining_ban_time">剩余封禁时间：{{ currentUser.remaining_ban_time }}</p>
            <p v-if="currentUser.ban_time && currentUser.ban_time !== '0001-01-01T00:00:00Z'">封禁时间：{{ formatDate(currentUser.ban_time) }}</p>
          </template>
        </el-alert>
      </div>
      <div v-if="currentUser" class="user-detail">
        <el-row :gutter="24">
          <!-- 左侧：用户详细信息 -->
          <el-col :span="8">
            <div class="user-info-container">
              <div class="user-header-info">
                <div class="avatar-container">
                  <el-avatar :size="100" :src="currentUser.avatar" />
                </div>
                <div class="info-header">
                  <h2>{{ currentUser.nickname || '未设置昵称' }}</h2>
                  <p class="signature">{{ currentUser.signature || '这个人很懒，什么都没写' }}</p>
                </div>
              </div>
              
              <el-divider />
              
              <div class="contact-info">
                <el-descriptions :column="1" border>
                  <el-descriptions-item label="用户ID">
                    <span>{{ currentUser.id }}</span>
                  </el-descriptions-item>
                  <el-descriptions-item label="手机号">
                    <span>{{ currentUser.phone }}</span>
                  </el-descriptions-item>
                  <el-descriptions-item label="邮箱">
                    <span>{{ currentUser.email || '未设置' }}</span>
                  </el-descriptions-item>
                  <el-descriptions-item label="注册时间">
                    <span>{{ formatDate(currentUser.register_time) }}</span>
                  </el-descriptions-item>
                  <el-descriptions-item label="账号状态">
                    <el-tag :type="getStatusType(currentUser.status)">{{ getStatusText(currentUser.status) }}</el-tag>
                  </el-descriptions-item>
                </el-descriptions>
              </div>
            </div>
          </el-col>
          
          <!-- 右侧：用户图片列表 -->
          <el-col :span="16">
            <div class="user-media-container">
              <!-- 用户图片列表 -->
              <div class="user-photos">
                <div class="photos-header">
                  <h3>上传的图片 ({{ currentUser.photos?.length || 0 }})</h3>
                </div>
                <el-empty v-if="!currentUser.photos?.length" description="暂无图片" />
                <el-scrollbar v-else height="500px">
                  <div class="photo-grid">
                    <div v-for="photo in currentUser.photos" :key="photo.id" class="photo-item">
                      <el-image
                        :src="photo.url"
                        :preview-src-list="getUserPhotosUrls()"
                        :initial-index="getUserPhotoIndex(photo.id)"
                        fit="cover"
                        class="grid-image"
                        preview-teleported
                        @click="handleImageClick(photo)"
                      >
                        <template #placeholder>
                          <div class="image-placeholder">
                            <el-icon><Picture /></el-icon>
                            <span>加载中...</span>
                          </div>
                        </template>
                        <template #error>
                          <div class="image-error">
                            <el-icon><PictureRounded /></el-icon>
                            <span>加载失败</span>
                          </div>
                        </template>
                      </el-image>
                      <div class="photo-info">
                        <p>上传时间：{{ formatDate(photo.uploaded_at) }}</p>
                        <p v-if="photo.category">分类：{{ photo.category }}</p>
                        <p v-if="photo.aperture">光圈：f/{{ photo.aperture }}</p>
                      </div>
                    </div>
                  </div>
                </el-scrollbar>
              </div>
            </div>
          </el-col>
        </el-row>
      </div>
    </el-dialog>

    <!-- 封禁用户对话框 -->
    <el-dialog
      v-model="banDialogVisible"
      :title="getDialogTitle(currentUser?.status)"
      width="40%"
    >
      <div v-if="currentUser?.status === 0" class="ban-form">
        <el-form ref="banFormRef" :model="banForm" label-width="100px">
          <el-form-item label="封禁时长" prop="days" :rules="[{ required: true, message: '请选择封禁时长' }]">
            <el-select v-model="banForm.days" placeholder="请选择封禁时长">
              <el-option label="1天" value="1" />
              <el-option label="3天" value="3" />
              <el-option label="7天" value="7" />
              <el-option label="30天" value="30" />
              <el-option label="永久" value="-1" />
            </el-select>
          </el-form-item>
          <!-- <el-form-item label="封禁原因">
            <el-input
              v-model="banForm.reason"
              type="textarea"
              rows="3"
              placeholder="请输入封禁原因"
            />
          </el-form-item> -->
        </el-form>
      </div>
      <div v-else-if="currentUser?.status === 1" class="unban-info">
        <el-alert
          type="warning"
          title="解除封禁"
          description="该操作将解除用户的封禁状态，解除后用户可正常登录使用。"
          show-icon
          :closable="false"
        />
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="banDialogVisible = false">取消</el-button>
          <el-button :type="getConfirmButtonType(currentUser?.status)" @click="handleBanStatusChange">
            {{ getConfirmButtonText(currentUser?.status) }}
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import request from '@/utils/request'
//import { useThemeStore } from '@/stores/theme'
import { Clock, Picture, PictureRounded } from '@element-plus/icons-vue'

// 表格数据
const loading = ref(false)
const userList = ref([])
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(10)
const searchKeyword = ref('')
const statusFilter = ref('')

// 当前选中的用户
const currentUser = ref(null)
const detailDialogVisible = ref(false)
const banDialogVisible = ref(false)

// 封禁表单
const banForm = ref({
  days: '',
  reason: ''
})

// 在script setup部分添加
const banFormRef = ref(null)

// 状态选项
const statusOptions = [
  { value: 0, label: '正常' },
  { value: 1, label: '临时封禁' },
  { value: 2, label: '已注销' },
  { value: 4, label: '软删除' },
  { value: -1, label: '永久封禁' }
]

// 获取警告框类型
const getAlertType = (status) => {
  switch (status) {
    case -1:
      return 'error';
    case 1:
      return 'warning';
    case 2:
      return 'info';
    case 4:
      return 'info';
    default:
      return 'info';
  }
}

// 获取状态类型
const getStatusType = (status) => {
  const statusMap = {
    0: 'success',
    1: 'warning',
    2: 'info',
    4: 'info',
    '-1': 'danger'
  }
  return statusMap[status] || 'info'
}

// 获取状态文本
const getStatusText = (status) => {
  const statusMap = {
    0: '正常',
    1: '临时封禁',
    2: '已注销',
    4: '软删除',
    '-1': '永久封禁'
  }
  return statusMap[status] || '未知状态'
}

// 格式化时间
const formatDate = (dateString) => {
  if (!dateString) return '-'
  const date = new Date(dateString)
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`
}

// 加载用户列表
const loadUserList = async () => {
  loading.value = true
  try {
    const params = {
      page: currentPage.value,
      pageSize: pageSize.value,
      keyword: searchKeyword.value
    }
    
    if (statusFilter.value !== '') {
      params.status = statusFilter.value
    }

    const res = await request.get('/user/list', { params })
    userList.value = res.data.data.list || []
    total.value = res.data.data.total || 0
  } catch (error) {
    console.error('加载用户列表失败:', error)
    ElMessage.error('加载列表失败')
  } finally {
    loading.value = false
  }
}

// 当前查看的图片
const currentPhoto = ref(null)

// 获取用户所有图片的URL列表，用于图片预览
const getUserPhotosUrls = () => {
  if (!currentUser.value || !currentUser.value.photos || !currentUser.value.photos.length) {
    return []
  }
  return currentUser.value.photos.map(photo => photo.url)
}

// 获取当前图片在图片列表中的索引
const getUserPhotoIndex = (photoId) => {
  if (!currentUser.value || !currentUser.value.photos) {
    return 0
  }
  const index = currentUser.value.photos.findIndex(photo => photo.id === photoId)
  return index > -1 ? index : 0
}

// 处理图片点击
const handleImageClick = (photo) => {
  currentPhoto.value = photo
  // 在这里可以添加其他处理逻辑，如记录查看历史等
}

// 查看用户详情
const viewUserDetail = async (user) => {
  try {
    currentUser.value = {
      ...user,
      photos: user.photos || [],
      email: user.email || '',
      nickname: user.nickname || '',
      signature: user.signature || '',
      status: user.status,
      remaining_ban_time: user.remaining_ban_time || '',
      register_time: user.register_time,
      ban_time: user.ban_time
    }
    detailDialogVisible.value = true
  } catch (error) {
    console.error('获取用户详情失败:', error)
    ElMessage.error('获取用户详情失败')
  }
}

// 处理封禁用户
const handleBanUser = (user) => {
  currentUser.value = user
  // 如果是永久封禁状态、注销状态或软删除状态，不允许操作
  if (user.status === -1) {
    ElMessage.warning('永久封禁状态不可修改')
    return
  }
  if (user.status === 2) {
    ElMessage.warning('注销账号不可操作')
    return
  }
  if (user.status === 4) {
    ElMessage.warning('软删除账号不可操作')
    return
  }
  banDialogVisible.value = true
  if (user.status === 0) {
    banForm.value = {
      days: '',
      reason: ''
    }
  }
}

// 处理封禁状态变更
const handleBanStatusChange = async () => {
  // 如果是解除封禁操作，直接发送请求
  if (currentUser.value.status === 1) {
    try {
      const url = `/user/unbanned/${currentUser.value.id}`
      await request.post(url, {})
      ElMessage.success('解封成功')
      banDialogVisible.value = false
      loadUserList()
    } catch (error) {
      console.error('操作失败:', error)
      ElMessage.error('操作失败')
    }
    return
  }
  
  // 如果是封禁操作，需要先验证表单
  if (!banFormRef.value) {
    console.error('表单引用不存在')
    ElMessage.error('系统错误')
    return
  }
  
  banFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        // 构建查询参数
        const days = parseInt(banForm.value.days, 10);
        const reason = banForm.value.reason || '';
        
        // 将参数作为查询参数发送
        const url = `/user/banned/${currentUser.value.id}?days=${days}&reason=${encodeURIComponent(reason)}`;
        
        await request.post(url);
        ElMessage.success('封禁成功');
        banDialogVisible.value = false;
        loadUserList();
      } catch (error) {
        console.error('操作失败:', error);
        ElMessage.error('操作失败');
      }
    } else {
      console.error('表单验证失败');
      return false;
    }
  })
}

// 删除用户
const handleDeleteUser = async (user) => {
  try {
    await ElMessageBox.confirm('确定要删除该用户吗？此操作不可恢复', '警告', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    await request.post(`/user/delete/${user.id}`)
    ElMessage.success('删除成功')
    loadUserList()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除用户失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

// 处理搜索
const handleSearch = () => {
  currentPage.value = 1
  loadUserList()
}

// 处理页码变化
const handleCurrentChange = (val) => {
  currentPage.value = val
  loadUserList()
}

// 处理每页条数变化
const handleSizeChange = (val) => {
  pageSize.value = val
  currentPage.value = 1
  loadUserList()
}

// 获取封禁按钮的类型
const getButtonType = (status) => {
  switch (status) {
    case 0:
      return 'warning'; // 封禁操作使用警告色
    case 1:
      return 'success'; // 解除封禁操作使用成功色
    case 4:
      return 'primary'; // 恢复软删除用户使用主要色
    case -1:
      return 'danger'; // 永久封禁显示为危险色
    default:
      return 'info'; // 其他情况使用信息色
  }
}

// 获取封禁按钮文本
const getBanButtonText = (status) => {
  switch (status) {
    case -1:
      return '永久封禁';
    case 0:
      return '封禁';
    case 1:
      return '解除封禁';
    case 2:
      return '已注销';
    case 4:
      return '已软删除';
    default:
      return '封禁';
  }
}

// 获取对话框标题
const getDialogTitle = (status) => {
  if (status === 0) return '封禁用户'
  return '解除封禁'
}

// 获取确认按钮类型
const getConfirmButtonType = (status) => {
  // 当状态为0时，是执行封禁操作，使用警告色
  // 当状态为1时，是执行解除封禁操作，使用成功色
  if (status === 0) return 'warning'
  return 'success'
}

// 获取确认按钮文本
const getConfirmButtonText = (status) => {
  if (status === 0) return '确认封禁'
  return '确认解除封禁'
}

// 设置表格单元格class
const tableCellClassName = () => {
  return 'compact-cell'
}

// 截断文本
const truncateText = (text, maxLength) => {
  if (!text) return ''
  if (text.length <= maxLength) return text
  return text.substring(0, maxLength) + '...'
}

// 首次加载
onMounted(() => {
  loadUserList()
})
</script>

<style scoped>
.users-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-box {
  display: flex;
  gap: 10px;
  align-items: center;
}

.search-box .el-input {
  width: 200px;
}

.search-box .el-select {
  width: 120px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.user-detail {
  margin-top: 20px;
}

.user-info-container {
  padding: 15px;
  background-color: #f9f9f9;
  border-radius: 8px;
  height: 100%;
}

.user-media-container {
  padding: 15px;
  background-color: #f9f9f9;
  border-radius: 8px;
  height: 100%;
  display: flex;
  flex-direction: column;
}

.user-photos {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.user-photos .el-scrollbar {
  flex: 1;
}

.user-header-info {
  display: flex;
  align-items: center;
  gap: 20px;
  margin-bottom: 20px;
}

.user-header-info .avatar-container {
  margin: 0;
}

.info-header {
  flex: 1;
}

.info-header h2 {
  font-size: 24px;
  margin: 0 0 8px 0;
  color: #303133;
}

.signature {
  font-size: 14px;
  color: #606266;
  font-style: italic;
  margin: 0;
}

.contact-info {
  margin-bottom: 24px;
}

.contact-info :deep(.el-descriptions__label) {
  width: 100px;
  font-weight: bold;
}

.avatar-container {
  display: flex;
  justify-content: center;
  margin-bottom: 24px;
}

.user-photos {
  margin-top: 24px;
}

.user-photos h3 {
  font-size: 18px;
  margin-bottom: 16px;
  color: #303133;
}

.photo-grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 16px;
  padding: 0 10px 10px 0;
}

.photo-item {
  background-color: #fff;
  border-radius: 4px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  transition: transform 0.2s;
}

.photo-item:hover {
  transform: translateY(-4px);
  box-shadow: 0 6px 12px rgba(0, 0, 0, 0.1);
}

.grid-image {
  width: 100%;
  height: 180px;
  object-fit: cover;
  border-radius: 4px 4px 0 0;
  cursor: pointer;
  transition: all 0.3s;
}

.photo-info {
  padding: 8px 12px;
  font-size: 12px;
  color: #606266;
}

.photo-info p {
  margin: 4px 0;
}

/* 暗黑模式适配 */
:deep(.el-dialog) {
  --el-dialog-bg-color: var(--el-bg-color);
}

.light-theme .user-info-container,
.light-theme .user-media-container {
  background-color: #f9f9f9;
}

.light-theme .stat-item {
  background-color: #fff;
}

.light-theme .photo-item {
  background-color: #fff;
}

.ban-info {
  margin-top: 15px;
  width: 100%;
}

.ban-info p {
  margin: 5px 0;
  font-size: 13px;
}

.ban-time {
  margin-top: 4px;
  font-size: 11px;
  color: #f56c6c;
}

.status-container {
  display: flex;
  align-items: center;
  gap: 4px;
  flex-wrap: wrap;
  justify-content: center;
  text-align: center;
}

.image-cell {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 1px 0;
  text-align: center;
}

.el-tooltip__trigger {
  display: inline-block;
  max-width: 200px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.el-tag {
  margin-left: 0;
}

.photos-header {
  margin-bottom: 16px;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

/* 图片预览相关样式 */
.image-placeholder,
.image-error {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  background-color: #f5f7fa;
  color: #909399;
  font-size: 12px;
}

.image-placeholder .el-icon,
.image-error .el-icon {
  font-size: 24px;
  margin-bottom: 8px;
}

/* 增强图片预览样式 */
.grid-image {
  cursor: pointer;
  transition: all 0.3s;
}

.grid-image:hover {
  transform: scale(1.03);
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}

/* 自定义图片查看器样式 */
:deep(.el-image-viewer__wrapper) {
  z-index: 3000;
}

:deep(.el-image-viewer__close) {
  color: #fff;
  font-size: 30px;
}

:deep(.el-image-viewer__actions) {
  opacity: 0.9;
  padding: 15px;
}

:deep(.el-image-viewer__prev),
:deep(.el-image-viewer__next) {
  width: 50px;
  height: 50px;
  font-size: 24px;
  color: #fff;
  background-color: rgba(0, 0, 0, 0.3);
  border-radius: 50%;
}

:deep(.el-image-viewer__img) {
  max-width: 90%;
  max-height: 90%;
}
</style>